package com.yzt.message;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yzt.zhuju.IService.message.IMessageService;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.base.BaseFragment;
import com.yzt.zhuju.constants.IntentConstant;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.dialog.CenterBaseDialog;
import com.yzt.zhuju.dialog.DefaultDialog;
import com.yzt.zhuju.dialog.NotifyPermissionsDialog;
import com.yzt.zhuju.event.im.RongYunExceptionEvent;
import com.yzt.zhuju.event.im.RongYunLoginSuccessEvent;
import com.yzt.zhuju.event.im.RongYunMessageUnreadStatusEvent;
import com.yzt.zhuju.event.main.MainSwitchEvent;
import com.yzt.zhuju.event.main.MessageListRefreshEvent;
import com.yzt.zhuju.event.message.MessageListAction;
import com.yzt.zhuju.event.message.MessageSendErrorEvent;
import com.yzt.zhuju.event.message.QuitGroupEvent;
import com.yzt.zhuju.utils.PermissionUtils;
import com.yzt.zhuju.utils.SystemUtil;
import com.yzt.zhuju.utils.TransferCacheUtils;
import com.yzt.zhuju.widget.popmenu.ActionMenuPopWindow;
import com.yzt.zhuju.widget.popmenu.MenuItem;
import com.yzt.zhuju.widget.recorddown.RecordDownLinearLayout;
import com.yzt.zhuju.widget.refreshHeader.WaterDropHeader;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.message.adapter.MessageListAdapter;
import com.yzt.message.util.ConversationMessageManager;
import com.yzt.message.fragment.MessageListSettingDialog;
import com.yzt.message.util.MessageInfoUtil;
import com.yzt.message.widget.TopLinearSmoothScroller;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import io.rong.common.RLog;
import io.rong.imkit.IMCenter;
import io.rong.imkit.config.ConversationListBehaviorListener;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversationlist.ConversationListAdapter;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.model.NoticeContent;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.widget.adapter.BaseAdapter;
import io.rong.imkit.widget.adapter.ViewHolder;
import io.rong.imkit.widget.refresh.constant.RefreshState;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * 会话列表页模块
 */
@SuppressLint("SetTextI18n")
public class MessageListFragment extends BaseFragment implements BaseAdapter.OnItemClickListener {

    private static final int REQUEST_OPEN_FLOW_WINDOW = 10000;

    private final String TAG = MessageListFragment.class.getSimpleName();

    protected ConversationListAdapter mAdapter = this.onResolveAdapter();

    private RecyclerView mList;

    private MessageListViewModel mConversationListViewModel;

    protected SmartRefreshLayout mRefreshLayout;

    protected Handler mHandler = new Handler(Looper.getMainLooper());

    private TextView tvRongCallback;

    /**
     * 通知栏容器
     */
    private RelativeLayout layoutOpenNotify;

    private RecordDownLinearLayout viewContent;

    public MessageListFragment() {
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewContent = view.findViewById(R.id.rc_content);
        this.mList = view.findViewById(R.id.rc_conversation_list);
        mList.setItemAnimator(null);

        this.mRefreshLayout = view.findViewById(R.id.rc_refresh);
        //暂时关闭下拉刷新
        this.mRefreshLayout.setEnableRefresh(true);
        this.mRefreshLayout.setEnableLoadMore(false);
        this.mAdapter.setItemClickListener(this);
        this.mAdapter.setEmptyView(R.layout.conversation_list_empty_layout);
        TopLinearSmoothScroller scroller = new TopLinearSmoothScroller(getActivity());

        //手动catch住
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
                super.smoothScrollToPosition(recyclerView, state, position);
                scroller.setTargetPosition(position);
                startSmoothScroll(scroller);
            }

            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
                try {
                    super.onLayoutChildren(recycler, state);
                } catch (IndexOutOfBoundsException e) {
                    //手动catch住
                    e.printStackTrace();
                }
            }
        };

        this.mList.setLayoutManager(linearLayoutManager);

        this.mList.setAdapter(this.mAdapter);

        this.initRefreshView();

        this.subscribeUi();

        // 点击重连
        tvRongCallback.setOnClickListener(v -> {

            if (rongExceptCode == 34001) {
                tvRongCallback.setVisibility(View.GONE);
                return;
            }

            if (rongExceptCode == -2
                    || rongExceptCode == 31002
                    || rongExceptCode == 31005
                    || rongExceptCode == 31008) {
                return;
            }

            if (rongExceptCode == 33001) {
                RouterAccount.LoginActivity(1);
                return;
            }

            // 重新连接
            ARouter.getInstance().navigation(IMessageService.class).login();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (this.mConversationListViewModel != null) {
            this.mConversationListViewModel.clearAllNotification();
        }
    }

    protected void initRefreshView() {

        //替换了融云的下拉刷新未自己的，统一UI 放开刷新功能
        this.mRefreshLayout.setNestedScrollingEnabled(true);
        this.mRefreshLayout.setRefreshHeader(new WaterDropHeader(mActivity));
        this.mRefreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));

        // 刷新列表
        this.mRefreshLayout.setOnRefreshListener(refreshLayout -> {
                    MessageListFragment.this.onConversationListRefresh();
                }
        );

        // 加载更多
        this.mRefreshLayout.setOnLoadMoreListener(refreshLayout ->
                MessageListFragment.this.onConversationListLoadMore()
        );
    }

    protected void onConversationListLoadMore() {
        if (this.mConversationListViewModel != null) {
            this.mConversationListViewModel.getConversationList(true, true);
        }
    }

    protected void onConversationListRefresh() {
        if (this.mConversationListViewModel != null) {
            this.mConversationListViewModel.getConversationList(false, true);
        }
    }

    protected ConversationListAdapter onResolveAdapter() {
        this.mAdapter = new MessageListAdapter();
        this.mAdapter.setEmptyView(R.layout.rc_conversationlist_empty_view);
        return this.mAdapter;
    }

    private int loadListAgain = 0;

    protected void subscribeUi() {

        this.mConversationListViewModel = (new ViewModelProvider(this)).get(MessageListViewModel.class);

        this.mConversationListViewModel.getConversationList(false, false);

        this.mConversationListViewModel.getConversationListLiveData().observe(this.getViewLifecycleOwner(), uiConversations -> {

                    if (loadListAgain == 0) {
                        loadListAgain++;
                        if (uiConversations != null && !uiConversations.isEmpty()) {
                            if (uiConversations.size() >= 2) {
                                String avatar = uiConversations.get(1).mCore.getPortraitUrl();
                                if (avatar == null || "".equals(avatar)) {
                                    MessageListFragment.this.onConversationListRefresh();
                                }
                            }
                            MessageListFragment.this.mAdapter.setDataCollection(uiConversations);
                        } else {
                            MessageListFragment.this.mAdapter.setDataCollection(uiConversations);
                        }
                    } else {
                        MessageListFragment.this.mAdapter.setDataCollection(uiConversations);
                    }
                }
        );

        this.mConversationListViewModel.getNoticeContentLiveData().observe(this.getViewLifecycleOwner(), noticeContent -> {
            if (MessageListFragment.this.tvRongCallback.getVisibility() == View.GONE) {
                MessageListFragment.this.mHandler.postDelayed(() ->
                        MessageListFragment.this.updateNoticeContent(MessageListFragment.this.mConversationListViewModel.getNoticeContentLiveData().getValue()), 4000L);
            } else {
                MessageListFragment.this.updateNoticeContent(noticeContent);
            }
        });

        this.mConversationListViewModel.getRefreshEventLiveData().observe(this.getViewLifecycleOwner(), refreshEvent -> {
            if (refreshEvent.state.equals(RefreshState.LoadFinish)) {
                MessageListFragment.this.mRefreshLayout.finishLoadMore();
            } else if (refreshEvent.state.equals(RefreshState.RefreshFinish)) {
                MessageListFragment.this.mRefreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onItemClick(View view, ViewHolder holder, int position) {

        if (position < 0) {
            return;
        }

        if (position >= this.mAdapter.getData().size()) {
            return;
        }

        BaseUiConversation baseUiConversation = this.mAdapter.getItem(position);
        ConversationListBehaviorListener listBehaviorListener = RongConfigCenter.conversationListConfig().getListener();
        if (listBehaviorListener != null && listBehaviorListener.onConversationClick(view.getContext(), view, baseUiConversation)) {
            RLog.d(this.TAG, "ConversationList item click event has been intercepted by App.");
        } else {
            if (baseUiConversation != null && baseUiConversation.mCore != null) {
                if (baseUiConversation instanceof GatheredConversation) {
                    RouteUtils.routeToSubConversationListActivity(view.getContext(), ((GatheredConversation) baseUiConversation).mGatheredType, baseUiConversation.mCore.getConversationTitle());
                } else {
                    RouteUtils.routeToConversationActivity(view.getContext(), baseUiConversation.mCore.getConversationType(), baseUiConversation.mCore.getTargetId());
                }
            } else {
                RLog.e(this.TAG, "invalid conversation.");
            }
        }
    }

    @Override
    public boolean onItemLongClick(final View view, ViewHolder holder, int position) {

        if (position < 0) {
            return false;
        } else {

            if (position >= this.mAdapter.getData().size()) {
                return false;
            }

            final BaseUiConversation baseUiConversation = this.mAdapter.getItem(position);

            // 如果是客服
            if ("10000".equals(baseUiConversation.mCore.getTargetId()) || "2".equals(baseUiConversation.mCore.getTargetId())) {
                return false;
            }

            ConversationListBehaviorListener listBehaviorListener = RongConfigCenter.conversationListConfig().getListener();
            if (listBehaviorListener == null || !listBehaviorListener.onConversationLongClick(view.getContext(), view, baseUiConversation)) {

                MenuItem deleteItem = new MenuItem();
                deleteItem.itemTitle = getString(R.string.delete);
                deleteItem.titleColor = Color.parseColor("#FF6550");
                deleteItem.clickListener = () -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(IntentConstant.INTENT_CANCEL, getString(R.string.cancel));
                    bundle.putString(IntentConstant.INTENT_SUBMIT, getString(R.string.confirm_delele));
                    bundle.putString(IntentConstant.INTENT_CONTENT, getString(R.string.and_remove_all_msg_record));
                    DefaultDialog fragment = (DefaultDialog) BaseDialog.showDialog(mActivity, DefaultDialog.class);
                    fragment.setArguments(bundle);
                    fragment.setListener(new DefaultDialog.OnSelectOnClickListener() {
                        @Override
                        public void selectSubmit() {
                            IMCenter.getInstance().removeConversation(baseUiConversation.mCore.getConversationType(), baseUiConversation.mCore.getTargetId(), null);
                            IMCenter.getInstance().deleteMessages(baseUiConversation.mCore.getConversationType(), baseUiConversation.mCore.getTargetId(), null);
                            RongIMClient.getInstance().cleanRemoteHistoryMessages(baseUiConversation.mCore.getConversationType(), baseUiConversation.mCore.getTargetId(), 0, null);
                        }

                        @Override
                        public void selectCancel() {

                        }
                    });
                };

                MenuItem setTopItem = new MenuItem();
                setTopItem.itemTitle = baseUiConversation.mCore.isTop() ? getString(R.string.cancel_to_top) : getString(R.string.to_top);
                setTopItem.clickListener = () -> IMCenter.getInstance().setConversationToTop(baseUiConversation.mCore.getConversationType(), baseUiConversation.mCore.getTargetId(), !baseUiConversation.mCore.isTop(), false, new RongIMClient.ResultCallback<Boolean>() {
                    @Override
                    public void onSuccess(Boolean value) {
                        ToastUtil.showMessage(setTopItem.itemTitle + getString(R.string.success), true, Gravity.CENTER);
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });

                ActionMenuPopWindow actionMenuPopWindow = new ActionMenuPopWindow.Builder()
                        .with(mActivity)
                        .addItem(deleteItem)
                        .addItem(setTopItem)
                        .build();
                float lastDownX = viewContent.getLastDownX();
                int screenWidth = DisplayUtils.getScreenWidth(mActivity);
                int xOffset;
                if (lastDownX > screenWidth / 2f) {
                    xOffset = (int) (lastDownX - DisplayUtils.dp2px(135));
                } else {
                    xOffset = (int) lastDownX;
                }
                actionMenuPopWindow.showAsDropDown(view, xOffset, -DisplayUtils.dip2px(150));
                actionMenuPopWindow.setOnDismissListener(() ->
                        view.setBackgroundColor(Color.TRANSPARENT)
                );

                view.setBackgroundColor(Color.parseColor("#11000000"));
            }
            return true;
        }
    }

    /**
     * 刷新错误通知状态
     */
    protected void updateNoticeContent(NoticeContent content) {
        if (content != null) {
            if (content.isShowNotice()) {
                this.tvRongCallback.setVisibility(View.VISIBLE);
                this.tvRongCallback.setText(content.getContent());
                if (content.getContent() == null || "".equals(content.getContent())) {
                    this.tvRongCallback.setVisibility(View.GONE);
                }
                if (content.getIconResId() != 0) {
                    this.tvRongCallback.setCompoundDrawablesRelativeWithIntrinsicBounds(content.getIconResId(), 0, 0, 0);
                }
            } else {
                this.tvRongCallback.setVisibility(View.GONE);
            }
        }
    }

    //----------------------上面的是ConversationListFragment源码部分---------------------------------------
    // 最后在这之后写自己的逻辑，方便后续的升级

    Handler newHandler = new Handler();

    private int displayMode;

    @Override
    public void netWorkRequest() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_message_main;
    }

    @Override
    public void installViews() {

        // 加载头部布局
        inflateHeaderView();

        // RxBus 回调
        initObserver();

        // 重新安装之后删除已读的消息
        delReadMessageAfterInstall();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    /**
     * 获取数据列表并刷新
     */
    private void getConversationList() {
        if (this.mConversationListViewModel != null) {
            this.mConversationListViewModel.getConversationList(false, false);
        }
    }

    /**
     * RxBus 回调
     */
    private void initObserver() {

        // 融云登录异常回调
        observerRxBus(RongYunExceptionEvent.class, event ->
                exceptionCallback(event.getExceptCode())
        );

        // 融云登录成功
        observerRxBus(RongYunLoginSuccessEvent.class, event -> {
                    if (tvRongCallback != null) {
                        tvRongCallback.setVisibility(View.GONE);
                    }
                    getConversationList();
                }
        );

        // 消息列表刷新
        observerRxBus(MessageListRefreshEvent.class, event ->
                MessageListFragment.this.mAdapter.setDataCollection(this.mConversationListViewModel.getUiConversationList())
        );

        // 消息发送失败
        observerRxBus(MessageSendErrorEvent.class, event -> newHandler.postDelayed(() ->
                RongIMClient.getInstance().getMessageByUid(event.getEntity().getMessageId(), new RongIMClient.ResultCallback<Message>() {
                    @Override
                    public void onSuccess(Message message) {
                        if (message == null) {
                            return;
                        }
                        message.setSentStatus(Message.SentStatus.FAILED);
                        RongIMClient.getInstance().setMessageSentStatus(message, null);
                        //通知页面刷新
                        IMCenter.getInstance().refreshMessage(message);
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                    }
                }), 500));

        // 融云未读刷新
        observerRxBus(RongYunMessageUnreadStatusEvent.class, event -> {
            newHandler.removeCallbacks(unReadRunnable);
            newHandler.postDelayed(unReadRunnable, 500);
            getConversationList();
        });

        observerRxBus(MessageListAction.class, event -> doMenuAction(event.getType()));

        // 退出群聊后删除群
        observerRxBus(QuitGroupEvent.class, event -> {
            IMCenter.getInstance().removeConversation(Conversation.ConversationType.GROUP, event.getRoomId(), null);
            IMCenter.getInstance().deleteMessages(Conversation.ConversationType.GROUP, event.getRoomId(), null);
            RongIMClient.getInstance().cleanRemoteHistoryMessages(Conversation.ConversationType.GROUP, event.getRoomId(), 0, null);
        });

        // 主模块底部按钮切换
        observerRxBus(MainSwitchEvent.class, event -> {
            if (event.getIndex() == 2 && !TransferCacheUtils.getTransferDataBool("showTipDialog")) {
                if (!SystemUtil.isNotificationEnable()) {
                    TransferCacheUtils.putTransferData("showTipDialog", true);
                    NotifyPermissionsDialog fragment = (NotifyPermissionsDialog)
                            CenterBaseDialog.showDialog(mActivity, NotifyPermissionsDialog.class);
                    fragment.setListener(flag -> {
                        if (!SharedPreferenceUtil.getInstance().getValue(PreferenceConstant.CLOSE_NOTIFY_TIP, false) && !flag) {
                            layoutOpenNotify.setVisibility(View.VISIBLE);
                        } else {
                            layoutOpenNotify.setVisibility(View.GONE);
                        }
                    });
                } else {
                    layoutOpenNotify.setVisibility(View.GONE);
                    SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.CLOSE_NOTIFY_TIP, true);
                }
            }
        });
    }

    /**
     * 更新未读消息
     */
    Runnable unReadRunnable = () -> {
        //未读的非系统消息
        List<BaseUiConversation> unReadConversations = new ArrayList<>();
        for (BaseUiConversation item : mAdapter.getData()) {
            if (!"0".equals(item.mCore.getTargetId()) && item.mCore.getUnreadMessageCount() > 0 && !MessageInfoUtil.isNeedFilter(item.mCore.getTargetId())) {
                unReadConversations.add(item);
            }
        }

        //记录当前未读消息数量
        ConversationMessageManager.getInstance().initConversation(unReadConversations);
    };

    /**
     * 融云回调异常code
     */
    private int rongExceptCode;

    /**
     * 处理融云异常Code
     */
    private void exceptionCallback(int rongyunExceptCode) {
        this.rongExceptCode = rongyunExceptCode;
        NoticeContent noticeContent = new NoticeContent();
        noticeContent.setShowNotice(true);
        noticeContent.setIconResId(R.mipmap.icon_message_error);
        if (rongyunExceptCode == -2) {
            noticeContent.setContent(getString(R.string.connect_loading));
        }
        if (rongyunExceptCode == -1) {
            noticeContent.setContent(getString(R.string.unkown_error));
        } else if (rongyunExceptCode == 31002) {
            noticeContent.setContent(getString(R.string.appkey_error));
        } else if (rongyunExceptCode == 31004) {
            noticeContent.setContent(getString(R.string.the_account_login_has_expired));
        } else if (rongyunExceptCode == 31005) {
            noticeContent.setContent(getString(R.string.app_verification_failed));
        } else if (rongyunExceptCode == 31008) {
            noticeContent.setContent(getString(R.string.app_ban_login_again));
        } else if (rongyunExceptCode == 31009) {
            noticeContent.setContent(getString(R.string.user_ban_login_again));
        } else if (rongyunExceptCode == 31020) {
            noticeContent.setContent(getString(R.string.account_expired_login_again));
        } else if (rongyunExceptCode == 33001) {
            noticeContent.setContent(getString(R.string.chat_init_ex_kill_app));
        } else if (rongyunExceptCode == 34006) {
            noticeContent.setContent(getString(R.string.connect_fail_try_again));
        } else {
            // 34001
            noticeContent.setContent(getString(R.string.connect_fail_try_again));
        }
        updateNoticeContent(noticeContent);
    }

    /**
     * 设置已读消息的类型
     */
    Conversation.ConversationType[] conversationTypes = new Conversation.ConversationType[]{
            Conversation.ConversationType.PRIVATE,
            Conversation.ConversationType.SYSTEM,
            Conversation.ConversationType.PUBLIC_SERVICE,
            Conversation.ConversationType.APP_PUBLIC_SERVICE
    };

    /**
     * pop消息窗操作按钮
     */
    private void doMenuAction(int type) {

        if (mAdapter == null) {
            return;
        }

        //list本体是CopyOnWriteArrayList，所以不用考虑线程问题,注意删除不能用迭代器的删除
        switch (type) {
            case MessageListSettingDialog.TYPE_SET_HAVE_READ: {
                // 消息设置已读
                IMManager.getInstance().clearMessageUnreadStatus(conversationTypes);

                if (mAdapter.getData() == null || mAdapter.getData().size() <= 0) {
                    return;
                }
                for (BaseUiConversation uiConversation : mAdapter.getData()) {
                    //未回复消息
                    if (getString(R.string.no_reply_message).equals(uiConversation.mCore.getConversationTitle())) {
                        uiConversation.mCore.setUnreadMessageCount(0);
                        break;
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
            break;
            case MessageListSettingDialog.TYPE_DELETE_ALL_MESSAGE:
                // 删除所有消息
                IMManager.getInstance().deleteMessage(conversationTypes);
                break;
            default:
                break;
        }

        // 获取会话消息列表
        getConversationList();
    }

    /**
     * 悬浮窗权限容器
     */
    private View llFloatTip;

    /**
     * 初始化列表头部view
     */
    private void inflateHeaderView() {
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.item_message_header, null);
        mAdapter.addHeaderView(headerView);
        ViewGroup.LayoutParams viewGroup = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(viewGroup);

        // 初始化权限通知
        initNotifyView(headerView);

        //融云回调提示
        tvRongCallback = headerView.findViewById(R.id.tv_rong_callback);

        //悬浮窗权限设置提醒
        initRequestFloatWindowView(headerView);
    }

    private void initRequestFloatWindowView(View headerView) {
        llFloatTip = headerView.findViewById(R.id.ll_float_tip);
        headerView.findViewById(R.id.tv_float_setting).setOnClickListener(v ->
                openFlowWidowPermissionActivity()
        );
        headerView.findViewById(R.id.iv_float_close).setOnClickListener(v -> llFloatTip.setVisibility(View.GONE));

        if (displayMode > 0) {
            llFloatTip.setVisibility(View.GONE);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(mActivity)) {
                llFloatTip.setVisibility(View.VISIBLE);
            } else {
                llFloatTip.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 跳转悬浮窗权限
     */
    private void openFlowWidowPermissionActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
            this.startActivityForResult(intent, REQUEST_OPEN_FLOW_WINDOW);
        }
    }

    /**
     * 初始化权限通知view
     */
    private void initNotifyView(View headerView) {
        layoutOpenNotify = headerView.findViewById(R.id.layout_open_notify);
        Button btnOpen = headerView.findViewById(R.id.btn_open);
        ImageView ivClose = headerView.findViewById(R.id.iv_close);
        btnOpen.setOnClickListener(v -> {
            PermissionUtils.openNotificationPermissionSetting(getContext());
            layoutOpenNotify.setVisibility(View.GONE);
        });
        ivClose.setOnClickListener(v -> {
            layoutOpenNotify.setVisibility(View.GONE);
            SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.CLOSE_NOTIFY_TIP, true);
        });

        // 判断通知权限是否打开
        if (SystemUtil.isNotificationEnable()) {
            layoutOpenNotify.setVisibility(View.GONE);
        } else {
            layoutOpenNotify.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 删除新安装后的重新拉取回来的已读消息
     */
    private void delReadMessageAfterInstall() {
        boolean isDelete = SharedPreferenceUtil.getInstance().getValue(PreferenceConstant.DELETE_HISTORY_MESSAGE(), true);
        if (isDelete) {
            if (!BuildConfig.DEBUG) {
                //设置debug下不删除消息
                handler.postDelayed(() -> {
                    IMManager.getInstance().deleteReadMessage(conversationTypes);
                    SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.DELETE_HISTORY_MESSAGE(), false);
                }, 4000);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_OPEN_FLOW_WINDOW == requestCode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(getActivity())) {
                    llFloatTip.setVisibility(View.GONE);
                }
            }
        }
    }
}